package com.baomidou.plugin.idea.mybatisx.advance.processor.clazz;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.plugin.idea.mybatisx.advance.util.PsiMethodUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * 给po的每个属性都生成一些只需要一个参数的方法
 * @author wanglei
 */
public class OneParamProcessor extends AbstractMPOnceMethodGenClassProcessor {

    private static final Logger log = Logger.getInstance(OneParamProcessor.class.getName());

    public static Set<String> ORDINARY_METHOD_NAMES = new HashSet<>();

    public static Set<String> LIKE_METHOD_NAMES = new HashSet<>();

    static {
        ORDINARY_METHOD_NAMES.add("lt");
        ORDINARY_METHOD_NAMES.add("le");
        ORDINARY_METHOD_NAMES.add("gt");
        ORDINARY_METHOD_NAMES.add("ge");
        ORDINARY_METHOD_NAMES.add("eq");
        ORDINARY_METHOD_NAMES.add("ne");
        LIKE_METHOD_NAMES.add("notLike");
        LIKE_METHOD_NAMES.add("like");
        LIKE_METHOD_NAMES.add("likeLeft");
        LIKE_METHOD_NAMES.add("likeRight");
    }

    private static final String CLASS_NAME = TableName.class.getName();

    public static final String METHOD_NAME = "oneParam";

    public OneParamProcessor() {
        super(CLASS_NAME, PsiMethod.class);
    }

    @Override
    String getMethodName() {
        return METHOD_NAME;
    }

    @NotNull
    public Collection<PsiMethod> createToStringMethod(@NotNull PsiClass psiClass, @NotNull PsiElement psiNavTargetElement) {
        List<PsiMethod> methods = new ArrayList<>();

        for (String methodName : ORDINARY_METHOD_NAMES) {
            methods.addAll(genMethodForFields(psiClass, psiNavTargetElement, methodName, false));
        }
        for (String methodName : LIKE_METHOD_NAMES) {
            methods.addAll(genMethodForFields(psiClass, psiNavTargetElement, methodName, true));
        }
        return methods;
    }

    /**
     * 给一个字段生成方法
     *
     * @param psiClass            class
     * @param psiNavTargetElement
     * @param methodName          方法名
     * @return
     */
    public List<PsiMethod> genMethodForFields(@NotNull PsiClass psiClass, @NotNull PsiElement psiNavTargetElement, String methodName, boolean isLike) {
        List<PsiMethod> methods = new ArrayList<>();
        final StringBuilder builder = new StringBuilder();
        String args = isLike ? "String arge" : "Comparable args";
        try {
            builder.append("public " + psiClass.getName() + " " + methodName + "(" + args + "){return this;}");
            methods.add(PsiMethodUtil.createMethod(psiClass, builder.toString(), psiNavTargetElement));
        } finally {
            //StringBuilderSpinAllocator.dispose(builder);
        }
        return methods;
    }
}
